
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <iostream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

using namespace std;

key_t key;
typedef struct msgbuff {
	long tp;
	char mm[100];
};
msgbuff mybuf;
int len, n, msgid;
char buf[100];
int maxlen;
	

void* msend(void*)
{
	mybuf.tp = 1;
	while(1) {
		fgets(buf, 100, stdin);
		len = strlen(buf);
		strcpy(mybuf.mm, buf);
		if(msgsnd(msgid, &mybuf, len, 0) < 0) {
			msgctl(msgid, IPC_RMID, NULL);
			exit(-1);
		}
		if(!strcmp(buf, "exit\n")) break;
	}
}

void* mrecv(void*)
{
	while(1) {
                if((len = msgrcv(msgid, &mybuf, maxlen, 0, 0)) < 0) {
                        exit(-1);
                }
                if(mybuf.tp == 300) {
                        cout << "end session" << endl;
                        msgctl(msgid, 0, 0);
                        exit(-1);
                }
                write(1, mybuf.mm, len);
                if(!strcmp(mybuf.mm, "exit\n")) {
                        cout << "end session !!"<< endl;
                        msgctl(msgid, 0, 0);
                        break;
                }
        }
}

int main()
{
	maxlen = 100;
	if((key = ftok("som.dat", 0)) < 0) {
		cout << "can't create key" << endl;
		exit(-1);
	}
	if((msgid = msgget(key, IPC_CREAT|0644)) < 0) {
		cout << "something is incorrect" << endl;
		exit(-1);
	}
	pthread_t t1, t2;
	createThread(&t1, NULL, mrecv, NULL);
	createThread(&t2, NULL, msend, NULL);
	pthreadJoin(t1, NULL);
	pthreadJoin(t2, NULL);	
	return 0;
}
